<!--
  控制台页面
-->
<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h1>控制台</h1>
      <p>欢迎回来，{{ authStore.userName }}！</p>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :xs="24" :sm="12" :md="6" v-if="authStore.hasPermission('question:read')">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon question">
              <el-icon size="32"><QuestionFilled /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ dashboardData.questionCount }}</div>
              <div class="stats-label">题目总数</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" v-if="authStore.hasPermission('exam:read')">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon exam">
              <el-icon size="32"><Document /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ dashboardData.examCount }}</div>
              <div class="stats-label">考试总数</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" v-if="authStore.hasPermission('grading:read')">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon grade">
              <el-icon size="32"><TrendCharts /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ dashboardData.gradeCount }}</div>
              <div class="stats-label">成绩记录</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon user">
              <el-icon size="32"><User /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ dashboardData.userCount }}</div>
              <div class="stats-label">在线用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="dashboard-content">
      <!-- 快速操作 -->
      <el-col :xs="24" :lg="8" v-if="authStore.hasRole(['teacher', 'admin'])">
        <el-card header="快速操作" class="quick-actions">
          <div class="action-grid">
            <el-button
              type="primary"
              :icon="Plus"
              @click="createExam"
              v-if="authStore.hasPermission('exam:write')"
            >
              创建考试
            </el-button>
            <el-button
              type="success"
              :icon="DocumentAdd"
              @click="createQuestion"
              v-if="authStore.hasPermission('question:write')"
            >
              添加题目
            </el-button>
            <el-button
              type="warning"
              :icon="Memo"
              @click="createPaper"
              v-if="authStore.hasPermission('paper:write')"
            >
              创建试卷
            </el-button>
            <el-button
              type="info"
              :icon="DataAnalysis"
              @click="viewGrades"
              v-if="authStore.hasPermission('grading:read')"
            >
              成绩分析
            </el-button>
          </div>
        </el-card>
      </el-col>

      <!-- 最近考试 -->
      <el-col :xs="24" :lg="authStore.hasRole(['teacher', 'admin']) ? 16 : 24">
        <el-card header="最近考试" class="recent-exams">
          <el-table :data="recentExams" style="width: 100%">
            <el-table-column prop="title" label="考试名称" />
            <el-table-column prop="exam_date" label="考试时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.exam_date) }}
              </template>
            </el-table-column>
            <el-table-column prop="duration" label="时长" width="100">
              <template #default="{ row }">
                {{ row.duration }}分钟
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button
                  text
                  type="primary"
                  @click="viewExamDetail(row)"
                >
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="table-footer">
            <el-button text @click="viewAllExams">
              查看全部考试 →
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 学习进度（学生专用） -->
    <el-row :gutter="20" class="dashboard-content" v-if="authStore.hasRole('student')">
      <el-col :xs="24" :lg="12">
        <el-card header="学习进度" class="learning-progress">
          <div class="progress-item" v-for="item in learningProgress" :key="item.subject">
            <div class="progress-header">
              <span class="subject-name">{{ item.subject }}</span>
              <span class="progress-percentage">{{ item.percentage }}%</span>
            </div>
            <el-progress
              :percentage="item.percentage"
              :color="getProgressColor(item.percentage)"
            />
            <div class="progress-info">
              <span>已完成: {{ item.completed }}</span>
              <span>总计: {{ item.total }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="12">
        <el-card header="最近成绩" class="recent-grades">
          <div class="grade-item" v-for="grade in recentGrades" :key="grade.id">
            <div class="grade-info">
              <div class="grade-title">{{ grade.exam_title }}</div>
              <div class="grade-date">{{ formatDate(grade.exam_date) }}</div>
            </div>
            <div class="grade-score" :class="getGradeClass(grade.score)">
              {{ grade.score }}分
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统公告 -->
    <el-row :gutter="20" class="dashboard-content">
      <el-col :xs="24">
        <el-card header="系统公告" class="system-notices">
          <div class="notice-list">
            <div
              class="notice-item"
              v-for="notice in systemNotices"
              :key="notice.id"
            >
              <div class="notice-content">
                <div class="notice-title">{{ notice.title }}</div>
                <div class="notice-description">{{ notice.description }}</div>
                <div class="notice-time">{{ formatDateTime(notice.created_at) }}</div>
              </div>
              <el-tag :type="getNoticeType(notice.type)" size="small">
                {{ getNoticeTypeText(notice.type) }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores'
import {
  QuestionFilled,
  Document,
  TrendCharts,
  User,
  Plus,
  DocumentAdd,
  Memo,
  DataAnalysis
} from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

// 模拟数据
const dashboardData = reactive({
  questionCount: 1234,
  examCount: 56,
  gradeCount: 789,
  userCount: 234
})

const recentExams = ref([
  {
    id: 1,
    title: '数学期末考试',
    exam_date: '2025-11-20 09:00:00',
    duration: 120,
    status: 'upcoming'
  },
  {
    id: 2,
    title: '英语听力测试',
    exam_date: '2025-11-15 14:00:00',
    duration: 60,
    status: 'completed'
  },
  {
    id: 3,
    title: '物理实验考试',
    exam_date: '2025-11-22 10:00:00',
    duration: 90,
    status: 'ongoing'
  }
])

const learningProgress = ref([
  {
    subject: '数学',
    percentage: 75,
    completed: 45,
    total: 60
  },
  {
    subject: '英语',
    percentage: 88,
    completed: 44,
    total: 50
  },
  {
    subject: '物理',
    percentage: 62,
    completed: 31,
    total: 50
  }
])

const recentGrades = ref([
  {
    id: 1,
    exam_title: '数学期中考试',
    exam_date: '2025-11-10',
    score: 85
  },
  {
    id: 2,
    exam_title: '英语单元测试',
    exam_date: '2025-11-08',
    score: 92
  },
  {
    id: 3,
    exam_title: '物理实验报告',
    exam_date: '2025-11-05',
    score: 78
  }
])

const systemNotices = ref([
  {
    id: 1,
    title: '系统维护通知',
    description: '系统将于本周六凌晨2点进行维护，预计持续2小时',
    created_at: '2025-11-17 10:00:00',
    type: 'maintenance'
  },
  {
    id: 2,
    title: '新功能上线',
    description: '智能组卷功能已上线，欢迎体验',
    created_at: '2025-11-16 15:30:00',
    type: 'feature'
  }
])

// 工具函数
const formatDateTime = (dateString: string) => {
  return new Date(dateString).toLocaleString()
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString()
}

const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    upcoming: 'info',
    ongoing: 'warning',
    completed: 'success'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    upcoming: '即将开始',
    ongoing: '进行中',
    completed: '已完成'
  }
  return texts[status] || '未知'
}

const getProgressColor = (percentage: number) => {
  if (percentage >= 80) return '#67c23a'
  if (percentage >= 60) return '#e6a23c'
  return '#f56c6c'
}

const getGradeClass = (score: number) => {
  if (score >= 90) return 'grade-excellent'
  if (score >= 80) return 'grade-good'
  if (score >= 60) return 'grade-pass'
  return 'grade-fail'
}

const getNoticeType = (type: string) => {
  const types: Record<string, string> = {
    maintenance: 'warning',
    feature: 'success',
    announcement: 'info'
  }
  return types[type] || 'info'
}

const getNoticeTypeText = (type: string) => {
  const texts: Record<string, string> = {
    maintenance: '维护',
    feature: '新功能',
    announcement: '公告'
  }
  return texts[type] || '通知'
}

// 事件处理
const createExam = () => {
  router.push('/examinations/create')
}

const createQuestion = () => {
  router.push('/questions/questions/create')
}

const createPaper = () => {
  router.push('/papers/templates/create')
}

const viewGrades = () => {
  router.push('/grading/analysis')
}

const viewAllExams = () => {
  router.push('/examinations/list')
}

const viewExamDetail = (exam: any) => {
  router.push(`/examinations/${exam.id}`)
}

// 加载仪表板数据
const loadDashboardData = async () => {
  try {
    // 这里调用API获取实际数据
    // const response = await getDashboardData()
    // Object.assign(dashboardData, response.data)
  } catch (error) {
    console.error('Failed to load dashboard data:', error)
  }
}

onMounted(() => {
  loadDashboardData()
})
</script>

<style scoped lang="scss">
.dashboard {
  .dashboard-header {
    margin-bottom: 24px;

    h1 {
      font-size: 28px;
      color: var(--el-text-color-primary);
      margin: 0 0 8px 0;
    }

    p {
      font-size: 16px;
      color: var(--el-text-color-regular);
      margin: 0;
    }
  }

  .stats-cards {
    margin-bottom: 24px;

    .stats-card {
      .stats-content {
        display: flex;
        align-items: center;

        .stats-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;

          &.question {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
          }

          &.exam {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
          }

          &.grade {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
          }

          &.user {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
            color: white;
          }
        }

        .stats-info {
          .stats-number {
            font-size: 24px;
            font-weight: bold;
            color: var(--el-text-color-primary);
            margin-bottom: 4px;
          }

          .stats-label {
            font-size: 14px;
            color: var(--el-text-color-regular);
          }
        }
      }
    }
  }

  .dashboard-content {
    margin-bottom: 24px;

    .quick-actions {
      .action-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;

        .el-button {
          height: 48px;
        }
      }
    }

    .recent-exams {
      .table-footer {
        text-align: center;
        margin-top: 16px;
      }
    }

    .learning-progress {
      .progress-item {
        margin-bottom: 20px;

        .progress-header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;

          .subject-name {
            font-weight: 500;
            color: var(--el-text-color-primary);
          }

          .progress-percentage {
            color: var(--el-color-primary);
          }
        }

        .progress-info {
          display: flex;
          justify-content: space-between;
          margin-top: 8px;
          font-size: 12px;
          color: var(--el-text-color-regular);
        }
      }
    }

    .recent-grades {
      .grade-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid var(--el-border-color-lighter);

        &:last-child {
          border-bottom: none;
        }

        .grade-info {
          .grade-title {
            font-weight: 500;
            color: var(--el-text-color-primary);
            margin-bottom: 4px;
          }

          .grade-date {
            font-size: 12px;
            color: var(--el-text-color-regular);
          }
        }

        .grade-score {
          font-size: 20px;
          font-weight: bold;

          &.grade-excellent {
            color: #67c23a;
          }

          &.grade-good {
            color: #409eff;
          }

          &.grade-pass {
            color: #e6a23c;
          }

          &.grade-fail {
            color: #f56c6c;
          }
        }
      }
    }

    .system-notices {
      .notice-list {
        .notice-item {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          padding: 16px 0;
          border-bottom: 1px solid var(--el-border-color-lighter);

          &:last-child {
            border-bottom: none;
          }

          .notice-content {
            flex: 1;

            .notice-title {
              font-weight: 500;
              color: var(--el-text-color-primary);
              margin-bottom: 4px;
            }

            .notice-description {
              font-size: 14px;
              color: var(--el-text-color-regular);
              margin-bottom: 8px;
            }

            .notice-time {
              font-size: 12px;
              color: var(--el-text-color-placeholder);
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .dashboard {
    .stats-cards {
      .stats-card {
        .stats-content {
          .stats-icon {
            width: 50px;
            height: 50px;
            margin-right: 12px;
          }

          .stats-info {
            .stats-number {
              font-size: 20px;
            }
          }
        }
      }
    }

    .dashboard-content {
      .quick-actions {
        .action-grid {
          grid-template-columns: 1fr;
        }
      }
    }
  }
}
</style>